Skip to content

codec, table: make new collation setting explicit in encoding (#69566)#69685

Merged
ti-chi-bot[bot] merged 7 commits into
pingcap:release-nextgen-202603from
ti-chi-bot:cherry-pick-69566-to-release-nextgen-202603
Jul 7, 2026
Merged

codec, table: make new collation setting explicit in encoding (#69566)#69685
ti-chi-bot[bot] merged 7 commits into
pingcap:release-nextgen-202603from
ti-chi-bot:cherry-pick-69566-to-release-nextgen-202603

Conversation

@ti-chi-bot

@ti-chi-bot ti-chi-bot commented Jul 6, 2026

Copy link
Copy Markdown
Member

This is an automated cherry-pick of #69566

What problem does this PR solve?

Issue Number: ref #69563

Problem Summary:

Some lower-level codec and tablecodec helper paths read the global new-collation setting directly when deciding how to encode values or whether restored data is needed. That makes deep utility behavior depend on process-wide state and makes the new-collation global harder to eliminate incrementally.

This PR is the first part of the refactor. It removes the implicit global dependency from the encoding paths touched here by threading an explicit collation setting through the relevant table, tablecodec, and codec helpers. Follow-up work should continue eliminating the remaining global variable usage.

in the first phase, we we will only refactor this part to make sure nextgen addindex/import-into can work in the case in the issue

What changed and how does it work?

  • Add codec.Encoder, which stores the new-collation setting used by EncodeKey, EncodeValue, and HashCode.
  • Keep the existing package-level codec functions as compatibility wrappers that still read the current global setting at the API boundary.
  • Thread codec.Encoder through row and index encoding helpers in tablecodec, table/tables, and table/tblctx.
  • Add explicit collation-setting variants for index construction and restored-data checks, including partial-index expression building.
  • Replace restored-data checks in these paths with NeedRestoredDataWithCollate when the collation setting is already known.
  • Update related tests and Bazel metadata.

Check List

Tests

  • Unit test
  • Integration test
  • Manual test (add detailed scripts or steps below)
  • No need to test
    • I checked and no code files have been changed.

Unit tests:

  • ./tools/check/failpoint-go-test.sh pkg/util/codec -run TestEncoderNewCollationEnabled -count=1
  • ./tools/check/failpoint-go-test.sh pkg/tablecodec -run 'Test(RowCodec|DecodeColumnValue|TimeCodec|CutRow|UniqueGlobalIndexKeyWithNullValues)$' -count=1
  • ./tools/check/failpoint-go-test.sh pkg/table/tables -run 'Test(CheckRowInsertionConsistency|CheckIndexKeysAndCheckHandleConsistency)$' -count=1
  • pushd pkg/table/tblctx >/dev/null && go test -run 'Test(EncodeRow|EncodeBufferReserve)$' -tags=intest,deadlock -count=1 && popd >/dev/null

Manual validation:

  • make bazel_prepare
  • git diff --check master...HEAD
  • make lint

Side effects

  • Performance regression: Consumes more CPU
  • Performance regression: Consumes more Memory
  • Breaking backward compatibility

Documentation

  • Affects user behaviors
  • Contains syntax changes
  • Contains variable changes
  • Contains experimental features
  • Changes MySQL compatibility

Release note

Please refer to Release Notes Language Style Guide to write a quality release note.

None

Summary by CodeRabbit

  • New Features

    • Added collation-aware encoding and index handling across row, key, and value operations for more consistent behavior with newer collation settings.
    • Session startup now loads system settings earlier so runtime behavior matches server configuration more reliably.
  • Bug Fixes

    • Fixed index recovery, row decoding, and consistency checks to honor the active collation mode.
    • Improved test and recovery paths to avoid mismatches when encoding or comparing string data under different collation settings.

D3Hunter added 7 commits July 6, 2026 11:07
use local new_collate settting

remove dependency

change

change

change

change

change
change

change
@ti-chi-bot ti-chi-bot added release-note-none Denotes a PR that doesn't merit a release note. sig/planner SIG: Planner size/XXL Denotes a PR that changes 1000+ lines, ignoring generated files. type/cherry-pick-for-release-nextgen-202603 labels Jul 6, 2026
@coderabbitai

coderabbitai Bot commented Jul 6, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Introduces a codec.Encoder type carrying a fixed collation mode, replacing scattered collate.NewCollationEnabled() checks in row/index encoding paths. Threads useNewCollate through tablecodec, table.Index, TableCommon, mutation checking, and expression rewriting; adds session-level global-var initialization from system DB; updates dependent tests and Bazel deps.

Changes

Collation-aware encoding refactor

Layer / File(s) Summary
Encoder primitive and collator helper
pkg/util/codec/codec.go, pkg/util/codec/codec_test.go, pkg/util/codec/collation_test.go, pkg/util/collate/collate.go, pkg/types/etc.go
Encoder struct with NewEncoder/UseNewCollate/EncodeKey/EncodeValue/HashCode is added; GetCollatorWithCollate and NeedRestoredDataWithCollate are introduced, with global-flag checks routed through NewCollationEnabled().
tablecodec row/index encode-decode signatures
pkg/tablecodec/tablecodec.go, pkg/tablecodec/tablecodec_test.go
EncodeRow, EncodeOldRow, GenIndexKey, GenIndexValuePortal, GenIndexValueForClusteredIndexVersion1, TryGetCommonPkColumnRestoredIds, and index KV decode helpers now take an Encoder/useNewCollate parameter.
Expression build options
pkg/expression/expression.go, pkg/meta/model/table.go
BuildOptions.UseNewCollate and WithUseNewCollate are added; model.ColumnNeedRestoredData is removed.
TableCommon/index encoder wiring
pkg/table/tables/tables.go, pkg/table/tables/index.go, pkg/table/tables/partition.go
TableCommon captures a fixed encoder; NewIndexWithCollate, CanSkip, and TryGetHandleRestoredDataWrapper thread useNewCollate through key/value generation and restore checks.
Mutation checker
pkg/table/tables/mutation_checker.go, pkg/table/tables/mutation_checker_test.go
checkIndexKeys/compareIndexData derive useNewCollate from the table encoder for decoding and collator selection; tests iterate both collation modes.
Row buffer encoder parameter
pkg/table/tblctx/buffers.go, pkg/table/tblctx/buffers_test.go, pkg/table/tblctx/BUILD.bazel
WriteMemBufferEncoded gains an explicit codec.Encoder parameter; EncodeBinlogRowData builds a collation-enabled encoder.
DDL, executor, planner callers
pkg/ddl/column.go, pkg/ddl/index.go, pkg/executor/admin.go, pkg/executor/write.go, pkg/planner/core/expression_rewriter.go
Backfill, admin recovery, write paths, and expressionRewriter now build/cache an encoder or useNewCollate flag rather than calling the global check inline.
Session global-var initialization
pkg/session/global_init.go, pkg/session/session.go, pkg/session/BUILD.bazel, pkg/testkit/mockstore.go
New initGlobalVarFromSystemDB loads system TZ and collation flag via a filtered domain, wired into bootstrap behind a skipInitGlobalVarFromSystemDB failpoint; old inline bootstrap logic removed.
Dependent test/Bazel updates
pkg/executor/test/executor/*, pkg/server/handler/tests/*, pkg/store/mockstore/*, pkg/util/rowDecoder/*, pkg/util/rowcodec/*, pkg/table/tables/testutil/*, tests/realtikvtest/addindextest2/*
Tests and Bazel deps updated to construct/pass a collation-enabled encoder into encoding/index-key calls.

Estimated code review effort: 4 (Complex) | ~75 minutes

Possibly related PRs

  • pingcap/tidb#69566: Both PRs thread an explicit codec.NewEncoder(collate.NewCollationEnabled())/useNewCollate through row/index key generation and restored-handle/data logic in the same core files.
  • pingcap/tidb#69658: Both PRs change how fetchRecoverRows computes/restores handle data via tables.TryGetHandleRestoredDataWrapper.

Suggested labels: approved, lgtm

Suggested reviewers: windtalker, YangKeao, qw4990, wjhuang2016

Poem

A hop, a skip, past collation's old flag,
Now each row carries its own little tag.
Encoder in paw, I carry it through,
Index and handle, restored anew.
No more global peeking, just what's passed along —
This bunny approves this collation-aware song! 🐇✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: making new-collation handling explicit across codec and table encoding paths.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Warning

Tools execution failed with the following error:

Failed to run tools: 13 INTERNAL: Received RST_STREAM with code 2 (Internal server error)


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@ti-chi-bot ti-chi-bot Bot added the needs-1-more-lgtm Indicates a PR needs 1 more LGTM. label Jul 6, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
pkg/table/tables/index.go (1)

63-70: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Update the now-stale initNeedRestoreData comment.

The comment states the lazy sync.Once is required because needRestoredData relies on NewCollationEnabled() and the collation global is initialized after NewIndex(). With this change, the collation mode is captured eagerly into encoder at construction, and GenIndexValue computes needRestoredData from the already-fixed c.encoder.UseNewCollate(). The sync.Once therefore no longer defers reading the global (its stated justification); it now only avoids recomputation. Please revise the comment so it doesn't mislead future readers about the collation ordering invariant.

As per coding guidelines: "Comments SHOULD explain non-obvious intent, constraints, invariants... SHOULD NOT restate what the code already makes clear".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/table/tables/index.go` around lines 63 - 70, Update the stale comment on
the initNeedRestoreData field in index state so it matches the current behavior:
it should explain that sync.Once is only used to avoid recomputing
needRestoredData, not because NewCollationEnabled() must be deferred until after
NewIndex(). Refer to initNeedRestoreData, needRestoredData, encoder, and
GenIndexValue in the comment text so it reflects that the collation choice is
now captured eagerly in the constructor and read from c.encoder.UseNewCollate().

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@pkg/table/tables/index.go`:
- Around line 63-70: Update the stale comment on the initNeedRestoreData field
in index state so it matches the current behavior: it should explain that
sync.Once is only used to avoid recomputing needRestoredData, not because
NewCollationEnabled() must be deferred until after NewIndex(). Refer to
initNeedRestoreData, needRestoredData, encoder, and GenIndexValue in the comment
text so it reflects that the collation choice is now captured eagerly in the
constructor and read from c.encoder.UseNewCollate().

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: a953bec0-b21b-483b-937e-e3bdd4b56828

📥 Commits

Reviewing files that changed from the base of the PR and between a9a0c38 and a8924b6.

📒 Files selected for processing (41)
  • pkg/ddl/column.go
  • pkg/ddl/index.go
  • pkg/executor/admin.go
  • pkg/executor/test/executor/BUILD.bazel
  • pkg/executor/test/executor/executor_test.go
  • pkg/executor/write.go
  • pkg/expression/expression.go
  • pkg/meta/model/table.go
  • pkg/planner/core/expression_rewriter.go
  • pkg/server/handler/tests/BUILD.bazel
  • pkg/server/handler/tests/http_handler_test.go
  • pkg/session/BUILD.bazel
  • pkg/session/global_init.go
  • pkg/session/session.go
  • pkg/store/mockstore/BUILD.bazel
  • pkg/store/mockstore/cluster_test.go
  • pkg/store/mockstore/unistore/cophandler/cop_handler_test.go
  • pkg/table/tables/index.go
  • pkg/table/tables/mutation_checker.go
  • pkg/table/tables/mutation_checker_test.go
  • pkg/table/tables/partition.go
  • pkg/table/tables/tables.go
  • pkg/table/tables/testutil/BUILD.bazel
  • pkg/table/tables/testutil/indexcheck.go
  • pkg/table/tblctx/BUILD.bazel
  • pkg/table/tblctx/buffers.go
  • pkg/table/tblctx/buffers_test.go
  • pkg/tablecodec/tablecodec.go
  • pkg/tablecodec/tablecodec_test.go
  • pkg/testkit/mockstore.go
  • pkg/types/etc.go
  • pkg/util/codec/codec.go
  • pkg/util/codec/codec_test.go
  • pkg/util/codec/collation_test.go
  • pkg/util/collate/collate.go
  • pkg/util/rowDecoder/BUILD.bazel
  • pkg/util/rowDecoder/decoder_test.go
  • pkg/util/rowcodec/bench_test.go
  • pkg/util/rowcodec/rowcodec_test.go
  • tests/realtikvtest/addindextest2/BUILD.bazel
  • tests/realtikvtest/addindextest2/global_sort_test.go
💤 Files with no reviewable changes (1)
  • pkg/meta/model/table.go

@D3Hunter

D3Hunter commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

/retest

@codecov

codecov Bot commented Jul 6, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 90.85714% with 16 lines in your changes missing coverage. Please review.
⚠️ Please upload report for BASE (release-nextgen-202603@a9a0c38). Learn more about missing BASE report.

Additional details and impacted files
@@                     Coverage Diff                     @@
##             release-nextgen-202603     #69685   +/-   ##
===========================================================
  Coverage                          ?   76.1626%           
===========================================================
  Files                             ?       1936           
  Lines                             ?     540560           
  Branches                          ?          0           
===========================================================
  Hits                              ?     411705           
  Misses                            ?     128855           
  Partials                          ?          0           
Flag Coverage Δ
unit 76.1626% <90.8571%> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

Components Coverage Δ
dumpling 61.4164% <0.0000%> (?)
parser ∅ <0.0000%> (?)
br 48.7548% <0.0000%> (?)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@ti-chi-bot ti-chi-bot Bot added lgtm and removed needs-1-more-lgtm Indicates a PR needs 1 more LGTM. labels Jul 7, 2026
@ti-chi-bot

ti-chi-bot Bot commented Jul 7, 2026

Copy link
Copy Markdown

[LGTM Timeline notifier]

Timeline:

  • 2026-07-06 11:13:53.671067653 +0000 UTC m=+21019.707162708: ☑️ agreed by D3Hunter.
  • 2026-07-07 01:31:20.104369738 +0000 UTC m=+72466.140464794: ☑️ agreed by joechenrh.

@windtalker windtalker left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

@ti-chi-bot

ti-chi-bot Bot commented Jul 7, 2026

Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: D3Hunter, GMHDBJD, joechenrh, qw4990, windtalker

The full list of commands accepted by this bot can be found here.

The pull request process is described here

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@ti-chi-bot ti-chi-bot Bot added the approved label Jul 7, 2026
@ti-chi-bot ti-chi-bot Bot merged commit 8b1d326 into pingcap:release-nextgen-202603 Jul 7, 2026
18 checks passed
@ti-chi-bot ti-chi-bot Bot deleted the cherry-pick-69566-to-release-nextgen-202603 branch July 7, 2026 02:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

approved lgtm release-note-none Denotes a PR that doesn't merit a release note. sig/planner SIG: Planner size/XXL Denotes a PR that changes 1000+ lines, ignoring generated files. type/cherry-pick-for-release-nextgen-202603

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants